package cn.piaoyi.web.action;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.piaoyi.bean.OrderGoods;
import cn.piaoyi.bean.OrderInfo;
import cn.piaoyi.bean.Price;
import cn.piaoyi.exception.PiaoyiException;
import cn.piaoyi.service.OrderGoodsService;
import cn.piaoyi.service.OrderInfoService;
import cn.piaoyi.service.PriceService;
import cn.piaoyi.web.interceptor.UserSessionAware;
import cn.piaoyi.web.servlet.UserSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.alipay.services.AlipayService;
import com.alipay.util.AlipayNotify;
import com.alipay.util.UtilDate;
import com.opensymphony.xwork2.ActionContext;

public class AlipayNotifyUrl extends BaseAction{
	private static final Log logger = LogFactory.getLog(AlipayNotifyUrl.class);
	private OrderInfoService orderInfoService;
	private OrderGoodsService orderGoodsService;
	private PriceService priceService;
	
	public OrderInfoService getOrderInfoService() {
		return orderInfoService;
	}

	public void setOrderInfoService(OrderInfoService orderInfoService) {
		this.orderInfoService = orderInfoService;
	}
	
	public OrderGoodsService getOrderGoodsService() {
		return orderGoodsService;
	}

	public void setOrderGoodsService(OrderGoodsService orderGoodsService) {
		this.orderGoodsService = orderGoodsService;
	}

	public PriceService getPriceService() {
		return priceService;
	}

	public void setPriceService(PriceService priceService) {
		this.priceService = priceService;
	}
	
	
	String trade_no;				//支付宝交易号
	String out_trade_no;	        //获取订单号
	String total_fee;	        	//获取总金额
	String subject;					//商品名称、订单名称
	String body = "";
	String buyer_email;				//买家支付宝账号
	String trade_status;			//交易状态

	public String getTrade_no() {
		return trade_no;
	}

	public void setTrade_no(String trade_no) {
		this.trade_no = trade_no;
	}

	public String getOut_trade_no() {
		return out_trade_no;
	}

	public void setOut_trade_no(String out_trade_no) {
		this.out_trade_no = out_trade_no;
	}

	public String getTotal_fee() {
		return total_fee;
	}

	public void setTotal_fee(String total_fee) {
		this.total_fee = total_fee;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public String getBuyer_email() {
		return buyer_email;
	}

	public void setBuyer_email(String buyer_email) {
		this.buyer_email = buyer_email;
	}

	public String getTrade_status() {
		return trade_status;
	}

	public void setTrade_status(String trade_status) {
		this.trade_status = trade_status;
	}

	public String execute() {
		try {
			return this.executeMethod(this.getAction());
		} catch (Exception e) {
			logger.error(e);
			return INPUT;
		}
	}

	/**
	 * 初始页
	 */
	public String index(){
		ActionContext context = ActionContext.getContext();  
	    HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
			params.put(name, valueStr);
		}
		if(AlipayNotify.verify(params)){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码

			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			
			if(trade_status.equals("TRADE_FINISHED")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					
				//注意：
				//该种交易状态只在两种情况下出现
				//1、开通了普通即时到账，买家付款成功后。
				//2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。
			} else if (trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
				OrderInfo oi = this.getOrderInfoService().findOrderInfoByOrderNO(this.out_trade_no);
				if(oi == null){
					
				}else{
					oi.setPayTime(new Date());
					oi.setOrderStatus(1);
					oi.setPayStatus(1);
					oi.setPayId(0);
					oi.setPayName("支付宝");
					try {
			        	this.getOrderInfoService().updateOrderInfo(oi);
			        } catch (PiaoyiException e) {
						this.addActionError(this.getText("error.orderinfo.updateerror"));
						return ERROR;
					}
			        List ogs = this.getOrderGoodsService().findOrderGoodses(oi.getId(), "id", 0);
			        for(int i=0;i<ogs.size();i++){
			        	OrderGoods og = (OrderGoods) ogs.get(i);
			        	Price p = this.getPriceService().findPriceById(og.getPriceId());
			        	p.setGoodsNumber(p.getGoodsNumber() - og.getGoodsNumber());
			        	try {
			        		this.getPriceService().updatePrice(p);
				        } catch (PiaoyiException e) {
							this.addActionError(this.getText("error.price.updateerror"));
							return ERROR;
						}
			        }  
				}	
				//注意：
				//该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。
			}

			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
				
			logger.info("success");	//请不要修改或删除——

			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
			logger.info("fail");
		}
		return null;
	}


}
